package com.esayread.ui.reading

import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.unit.dp

@Composable
fun HtmlContentRenderer(
    htmlContent: String,
    modifier: Modifier = Modifier,
    onLinkClick: ((String) -> Unit)? = null
) {
    val context = LocalContext.current
    val backgroundColor = MaterialTheme.colorScheme.surface.toArgb()
    val textColor = MaterialTheme.colorScheme.onSurface.toArgb()
    
    // 构建完整的HTML文档
    val fullHtml = buildString {
        append("<!DOCTYPE html>")
        append("<html><head>")
        append("<meta charset='UTF-8'>")
        append("<meta name='viewport' content='width=device-width, initial-scale=1.0'>")
        append("<style>")
        append("""
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                font-size: 18px;
                line-height: 1.8;
                color: #${String.format("%06X", 0xFFFFFF and textColor)};
                background-color: #${String.format("%06X", 0xFFFFFF and backgroundColor)};
                margin: 0;
                padding: 20px;
                text-align: justify;
            }
            
            h1, h2, h3, h4, h5, h6 {
                font-weight: 600;
                margin: 24px 0 16px 0;
                line-height: 1.4;
            }
            
            h1 { font-size: 28px; }
            h2 { font-size: 24px; }
            h3 { font-size: 20px; }
            
            p {
                margin: 16px 0;
                text-indent: 2em;
            }
            
            img {
                max-width: 100%;
                height: auto;
                display: block;
                margin: 16px auto;
                border-radius: 8px;
            }
            
            blockquote {
                border-left: 4px solid #ccc;
                margin: 16px 0;
                padding: 8px 16px;
                background-color: rgba(128, 128, 128, 0.1);
                font-style: italic;
            }
            
            ul, ol {
                margin: 16px 0;
                padding-left: 24px;
            }
            
            li {
                margin: 8px 0;
            }
            
            a {
                color: #007AFF;
                text-decoration: none;
            }
            
            a:hover {
                text-decoration: underline;
            }
            
            table {
                width: 100%;
                border-collapse: collapse;
                margin: 16px 0;
            }
            
            th, td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }
            
            th {
                background-color: rgba(128, 128, 128, 0.1);
                font-weight: 600;
            }
            
            .chapter-title {
                text-align: center;
                margin: 32px 0;
                font-size: 24px;
                font-weight: 700;
            }
            
            .toc-link {
                display: block;
                padding: 8px 0;
                border-bottom: 1px dotted #ccc;
                color: #007AFF;
            }
        """.trimIndent())
        append("</style>")
        append("</head><body>")
        append(htmlContent)
        append("</body></html>")
    }
    
    AndroidView(
        factory = { ctx ->
            WebView(ctx).apply {
                webViewClient = object : WebViewClient() {
                    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                        // 允许页面内锚点跳转由 WebView 自行处理
                        if (url != null && url.startsWith("#")) return false
                        url?.let { onLinkClick?.invoke(it) }
                        return true
                    }
                    
                    override fun shouldOverrideUrlLoading(view: WebView?, request: android.webkit.WebResourceRequest?): Boolean {
                        val target = request?.url?.toString()
                        if (target != null && target.startsWith("#")) return false
                        target?.let { onLinkClick?.invoke(it) }
                        return true
                    }
                }
                
                settings.apply {
                    javaScriptEnabled = false // 安全考虑，禁用JavaScript
                    domStorageEnabled = false
                    allowFileAccess = false
                    allowContentAccess = false
                    setSupportZoom(true)
                    builtInZoomControls = true
                    displayZoomControls = false
                }
                
                setBackgroundColor(backgroundColor)
            }
        },
        update = { webView ->
            webView.loadDataWithBaseURL(
                null,
                fullHtml,
                "text/html",
                "UTF-8",
                null
            )
        },
        modifier = modifier
    )
}

@Composable
fun TableOfContentsRenderer(
    tocItems: List<com.esayread.reader.TocItem>,
    onTocItemClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val tocHtml = buildString {
        append("<div class='toc-container'>")
        append("<h2 class='chapter-title'>目录</h2>")
        tocItems.forEach { item ->
            append("<a href='${item.href}' class='toc-link'>${item.title}</a>")
        }
        append("</div>")
    }
    
    HtmlContentRenderer(
        htmlContent = tocHtml,
        onLinkClick = onTocItemClick,
        modifier = modifier
    )
}